package com.p2l.letterblocks;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Paint.Align;
import android.os.Build;

public class Block extends Sprite {
	private GamePersistor persistor;
	private Rect bounds;
	private float scale;
	private char letter;
	
	public Block(GamePersistor persistor, float x, float y, float height, float width, Bitmap bitmap, char letter, float scale, int color) {
		super(x, y, height, width, bitmap);
		this.persistor = persistor;
		this.letter = letter;
		this.scale = scale;
		
		getPaint().setColor(color);
		getPaint().setTextSize(persistor.getResources().getDimension(R.dimen.text_ingame_letterblocks));
		bounds = new Rect();
		getPaint().setTextAlign(Align.CENTER);
	}

	public char getLetter() {
		return letter;
	}

	public void setLetter(char letter) {
		this.letter = letter;
	}

	@Override
	public void onDraw(Canvas c, int delta, float x) {
		float newY = getY() + (getVector().getY() * delta);
		Rect r = new Rect((int)(getX() - x), (int)(newY), (int)(getX() - x + getWidth()), (int)(newY + getHeight()));
		c.drawBitmap(getBitmap(), null, r, getPaint());
		
		getPaint().getTextBounds("" + letter, 0, 1, bounds);
	    int letterY = (int)(getHeight() + bounds.height()) / 2; 
		int letterX = (int)(getX() - x + (getWidth() / 2));
		
		if (Build.VERSION.SDK_INT <= 10) {
			if (letter == 'Q')
				letterY -= getHeight() / 8;
			else if (letter == 'J')
				letterY -= getHeight() / 6;
		}
		
		c.drawText("" + letter, letterX, getY() + letterY, getPaint());
	}
	
	public void update(int delta) {
		getVector().setY(getVector().getY() + (GamePersistor.SCREEN_HEIGHT / Vector.GRAVITY) * delta);
		setY(getY() + getVector().getY() * delta);
		setX(getX() + getVector().getX() * delta);
		
		// floor collision detection
		float bottom = GamePersistor.SCREEN_HEIGHT - getHeight() - (GamePersistor.SCREEN_HEIGHT / 100 * GameView.BOTTOM);
		if (getY() > bottom) {
			setY(bottom);
			getVector().setY(0f);
		}
	}
	
	public boolean isColliding(Sprite s) {
		if (getX() <= s.getX() + s.getWidth() && getX() + getWidth() >= s.getX() && getY() <= s.getY() + s.getHeight() && getY() + getHeight() >= s.getY())
			return true;
		else
			return false;
	}
}